package com.ccc.excel.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.ccc.excel.pojo.ExcelExportStyler;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Excel 导入导出工具类
 *
 * @author superC
 * @version 1.0.0
 * @date 2020/11/25
 */

public class MyExcelUtils {

    protected static final Logger logger = LoggerFactory.getLogger(MyExcelUtils.class);

    private static final String OCTET_STREAM = "application/octet-stream";
    private static final String MS_EXCEL = "application/vnd.ms-excel";


    /*  ********************************     下载     ************************************ */

    /**
     * 生成excel文件
     *
     * @param list      数据
     * @param title     标题
     * @param sheetName sheet名称
     * @param pojoClass pojo类型
     * @param fileName  文件名称
     */
    public static void generateExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        // 设置样式
        exportParams.setStyle(ExcelExportStyler.class);

        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downloadExcel(fileName, workbook);
    }

    /**
     * 下载
     *
     * @param filePath
     * @param workbook
     */
    private static void downloadExcel(String filePath, Workbook workbook) {
        OutputStream outStream = null;
        try {
            outStream = new FileOutputStream(filePath);
            workbook.write(outStream);
        } catch (IOException e) {
            logger.error("【捕获异常-IO异常】\r\n异常记录：", e);
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                logger.error("【捕获异常-IO异常】\r\n异常记录：", e);
            }
        }
    }


    /*  ********************************     导出     ************************************ */

    /**
     * excel导出
     *
     * @param list           数据
     * @param title          标题
     * @param sheetName      sheet名称
     * @param pojoClass      pojo类型
     * @param fileName       文件名称
     * @param isCreateHeader 是否创建表头
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel导出
     *
     * @param list      数据
     * @param pojoClass pojo类型
     * @param title     标题
     * @param sheetName sheet名称
     * @param fileName  文件名称
     * @param response
     */
    public static void exportExcel(List<?> list, Class<?> pojoClass, String title, String sheetName, String fileName, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        // 设置样式
        exportParams.setStyle(ExcelExportStyler.class);

        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * 默认的excel导出
     *
     * @param list         数据
     * @param pojoClass    pojo类型
     * @param fileName     文件名称
     * @param response
     * @param exportParams 导出参数
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        doExport(fileName, response, workbook);
    }

    /**
     * excel导出多Sheet
     *
     * @param listMap:         已经分组后数据
     * @param clazz:        实体类class
     * @param fileName:     文件名称
     * @param titleName:    标题
     * @param response:
     * @date 2023-10-29 23:38
     * @author superC
     */
    public static <T, K> void exportExcelToMutiSheet(Map<String, List<T>> listMap, Class<?> clazz, String fileName, String titleName, HttpServletResponse response) throws IOException {
        //省略查询步骤
        List<Map<String, Object>> mapList = new ArrayList<>();
        listMap.forEach((k, v) -> {
            ExportParams exportParams = new ExportParams(titleName, k, ExcelType.XSSF);
            Map<String, Object> map = new HashMap<>();
            map.put("title", exportParams);
            map.put("entity", clazz);
            map.put("data", v);
            mapList.add(map);
        });
        mutiSheetExport(mapList, fileName, response);
    }

    /**
     * excel导出多Sheet
     *
     * @param list:         全部数据
     * @param clazz:        实体类class
     * @param keyExtractor: 分组字段
     * @param fileName:     文件名称
     * @param titleName:    标题
     * @param response:
     * @date 2023-10-29 23:38
     * @author superC
     */
    public static <T, K> void exportExcelToMutiSheet(List<T> list, Class<?> clazz, Function<T, String> keyExtractor, String fileName, String titleName, HttpServletResponse response) throws IOException {
        //省略查询步骤
        Map<String, List<T>> listMap = list.stream().collect(Collectors.groupingBy(keyExtractor));
        List<Map<String, Object>> mapList = new ArrayList<>();
        listMap.forEach((k, v) -> {
            ExportParams exportParams = new ExportParams(titleName, k, ExcelType.XSSF);
            Map<String, Object> map = new HashMap<>();
            map.put("title", exportParams);
            map.put("entity", clazz);
            map.put("data", v);
            mapList.add(map);
        });
        mutiSheetExport(mapList, fileName, response);
    }

    /**
     * excel导出多Sheet
     *
     * @param list     数据
     * @param fileName 文件名称
     * @param response
     */
    private static void mutiSheetExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        doExport(fileName, response, workbook);
    }

    /**
     * response导出
     *
     * @param fileName 文件名称
     * @param response
     * @param workbook excel数据
     */
    private static void doExport(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", MS_EXCEL);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }


    /*  ********************************     导入     ************************************ */

    /**
     * excel 导入
     *
     * @param filePath   excel文件路径
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param pojoClass  pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setNeedSave(true);
        params.setSaveUrl("/excel/");
        try {
            return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("模板不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param file      excel文件
     * @param pojoClass pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
        return importExcel(file, 1, 1, pojoClass);
    }

    /**
     * excel 导入
     *
     * @param file       excel文件
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param pojoClass  pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        return importExcel(file, titleRows, headerRows, false, pojoClass);
    }

    /**
     * excel 导入
     *
     * @param file       上传的文件
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param needVerfiy 是否检验excel内容
     * @param pojoClass  pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException {
        if (file == null) {
            return null;
        }
        try {
            return importExcel(file.getInputStream(), titleRows, headerRows, needVerfiy, pojoClass);
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param inputStream 文件输入流
     * @param titleRows   标题行
     * @param headerRows  表头行
     * @param needVerfiy  是否检验excel内容
     * @param pojoClass   pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException {
        if (inputStream == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSaveUrl("/excel/");
        params.setNeedSave(true);
        params.setNeedVerify(needVerfiy);
        try {
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * Excel 类型枚举
     */
    enum ExcelTypeEnum {
        XLS("xls"), XLSX("xlsx");
        private String value;

        ExcelTypeEnum(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

}
